<template>
  <div
    class="w-3/5 mx-auto overflow-y-auto pr-10 pt-10 max-h-[550px] 2xl:max-h-[1050px] flex-1 scrollBarY"
    ref="chatContainerRef"
    @scroll="handleScroll"
  >
    <Bubble.List :items="items" :roles="roles" />
  </div>
</template>

<script setup lang="ts">
import { Bubble } from 'ant-design-x-vue'
import { ref, nextTick, watch } from 'vue'
import type { BubbleListProps } from 'ant-design-x-vue'

const props = defineProps<{
  items: BubbleListProps['items']
  roles: BubbleListProps['roles']
}>()

const chatContainerRef = ref<HTMLElement | null>(null)
const autoScrollEnabled = ref(true) // 是否自动滚动

// 滚动到最新消息
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainerRef.value && autoScrollEnabled.value) {
    chatContainerRef.value.scrollTo({
      top: chatContainerRef.value.scrollHeight,
      behavior: 'smooth',
    })
  }
}

// 检测用户是否在底部
const handleScroll = () => {
  if (!chatContainerRef.value) return

  const { scrollTop, scrollHeight, clientHeight } = chatContainerRef.value
  const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10 // 允许一点误差

  autoScrollEnabled.value = isAtBottom
}

// 当消息更新时，如果允许自动滚动就滚到底
watch(
  () => props.items,
  () => {
    scrollToBottom()
  },
  { deep: true },
)
</script>
